package com.zhiyou.app.shop.common;

import java.lang.reflect.Method;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.zhiyou.app.shop.manager.dao.pojo.UserDetail;

public class AuthorityInterceptor implements Interceptor {

	public void destroy() {
		
	}

	public void init() {
		
	}

	public String intercept(ActionInvocation invocation) throws Exception {
		Object obj = ServletActionContext.getRequest().getSession().getAttribute("user");
		UserDetail ud = null;
		if(null != obj && obj instanceof UserDetail){
			ud = (UserDetail) obj;
		}
		String methodName=invocation.getProxy().getMethod();
        Method currentMethod=invocation.getAction().getClass().getMethod(methodName, null);
        if(currentMethod.isAnnotationPresent(Authority.class)){
        	if(null == ud) return "login";
        	Authority authority = currentMethod.getAnnotation(Authority.class);
        	int role = authority.value();
        	if(ud.getRole() > role){
        		throw new Exception("您无权访问该页面");
        	}
        }
		return invocation.invoke();
	}

}
